package com.pactera.madp.cp.config;

import com.pactera.madp.cp.job.WorkMsgBackUpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 会话存档初始化加载依赖
 */
@Slf4j
@Configuration
public class FinanceConfig {

    @Value("${madp.jni-libs}")
    private String jniLibs;

    @EventListener({WebServerInitializedEvent.class})
    public void init() {
        if(loadLib()) {
            WorkMsgBackUpUtil.setSdk();
            log.info("---会话存档SDK加载成功---");
        }
    }

    private boolean isWindows() {
        String osName = System.getProperties().getProperty("os.name");
        log.info("current system is " + osName);
        return osName.toUpperCase().indexOf("WINDOWS") != -1;
    }

    @SneakyThrows
    private boolean loadLib() {
        if (isWindows()) {
            System.loadLibrary("WeWorkFinanceSdk");
            return true;
        }

        //源文件
        String resourcePath = jniLibs;
        File srcFile = new File(resourcePath);
        String libName = srcFile.getName();
        //目标文件
        String folderName = System.getProperty("java.io.tmpdir") + "/lib/jniLibs/";
        File folder = new File(folderName);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File libFile = new File(folder, libName);
        //是否相同路径
        if(libFile.getAbsolutePath().equals(srcFile.getAbsolutePath())) {
            System.load(libFile.getAbsolutePath());
            return true;
        }
        //文件拷贝
        InputStream inputStream = new FileInputStream(resourcePath);
        FileUtils.copyInputStreamToFile(inputStream, libFile);
        //加载依赖
        System.load(libFile.getAbsolutePath());

        return true;
    }
}
